<?php
/**
 * 直播回放
 */

namespace app\live\controller\api;

use app\ApiController;
use think\Db;

class LiveBack extends ApiController
{

    /*
        回调数据格式
        {
            "event_type":100,
            "appid":12345678,
            "app":yourapp
            "appname":yourappname
            "stream_id":"stream_test",
            "channel_id":"stream_test",
            "file_id":"1234567890",
            "file_format":"hls",
            "task_id":"UpTbk5RSVhRQ********************0xTSlNTQltlRVRLU1JAWW9EUb",
            "start_time":1545047010,
            "end_time":1545049971,
            "duration":2962,
            "file_size":277941079,
            "stream_param":"stream_param=test",
            "video_url":"http://12345678.vod2.myqcloud.com/xxxx/yyyy/zzzz.m3u8",
            "sign":"ca3e25e**********09a9ae7281e300d",
            "t":1545030873
        }
    */
    function index()
    {
        $request = file_get_contents("php://input");

        $result = array('code' => 0);
        $data = json_decode($request, true);

        if (!$data) {
            $result['code'] = 4001;
            $result['msg'] = 'request para json format error';
            echo json_encode($result);
            exit;
        }

        if (array_key_exists("event_type", $data) && array_key_exists("stream_id", $data)) {
            $event_type = $data['event_type'];
            $stream_id = $data['stream_id'];
        } else {
            $result['code'] = 4002;
            $result['msg'] = 'request para error';
            echo json_encode($result);
            exit;
        }

        if ($event_type == 100) {
            /* 回放回调 */
            if (array_key_exists("video_id", $data) &&
                array_key_exists("video_url", $data) &&
                array_key_exists("start_time", $data) &&
                array_key_exists("end_time", $data)) {

                $video_id = $data['video_id'];
                $video_url = $data['video_url'];
                $start_time = $data['start_time'];
                $end_time = $data['end_time'];
            } else {
                $result['code'] = 4002;
                $result['msg'] = 'request para error:回放信息参数缺少';
                echo json_encode($result);
                exit;
            }
        }
        $ret = 0;
        if ($event_type == 0) {
            /* 断流回调  toDo*/
        } elseif ($event_type == 1) {
            /* 推流回调 toDo*/
        } elseif ($event_type == 100) {
            /* 录制回调 */
            $data = array(
                "video_url" => $video_url,
                "live_replay" => $request,
                "is_replay" => 1,
            );
            Db::table("live_room")->where(["stream_id" => $stream_id])->update($data);
        }
        $result['code'] = $ret;
        echo json_encode($result);
        exit;

    }


}